package cn.rzpt.demo;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * MyBatis工具类
 * @author zsm
 *
 */
public class MyBatisUtil {
	private static SqlSessionFactory sqlSessionFactory;
	//静态代码块
	static {
		//mybatis 配置文件所在位置
		String resource = "cn/rzpt/demo/mybatis-config.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建 Session
	 * @return
	 */
	public static SqlSession createSession() {
		return sqlSessionFactory.openSession();
	}
	/**
	 * 关闭一个sqlSession
	 * @param session
	 */
	public static void closeSqlSession(SqlSession session) {
		if(null != session) {
			session.close();
		}
	}
	
}
